package com.hz.erp.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 柯鑫
 * @ClassName com.hz.erp.utils.SendSmsUtil
 * @description 发送短信模板
 * @create 2020年06月18日 17:35
 */

public class SendSmsUtil {

    public static String sendMessage(String phoneNumbers, HttpServletRequest httpServletRequest){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4KLBeG9ASEnT", "vrI2ph48ynhzJckiBqb1okIc0YfbFS");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        //接收短信的手机号码
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        //短信签名名称
        request.putQueryParameter("SignName", "天付支付");
        //短信签名名称
        request.putQueryParameter("TemplateCode", "SMS_151548354");
        //短信模板变量对应的实际值，JSON格式。
        String code = verifyCode();
        request.putQueryParameter("TemplateParam", code);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());

            JSONObject jsonObject = JSON.parseObject(response.getData());
            HttpSession session = httpServletRequest.getSession();

            session.setAttribute("phoneCode", code);
            session.setMaxInactiveInterval(60*5);
            System.out.println("发送............." +session.getId());

            return jsonObject.getString("Code");
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    return null;
    }

    /**
     * 生成6位验证码
     * @return
     */
    public static String verifyCode(){
        Map map = new HashMap<>();
        String verifyCode = String.valueOf((int)(Math.random()*900000 + 100000));
        map.put("code", verifyCode);
        return JSON.toJSONString(map);
    }


}
